/*
 * @Author: your name
 * @Date: 2022-02-22 16:30:24
 * @LastEditTime: 2022-04-04 10:52:19
 * @LastEditors: Please set LastEditors
 * @Description: 文章列表查询界面
 * @FilePath: \blog_system\src\Pages\Article\ArticleList.js
 */

import { Button, Table, Tag, Space, notification, Image } from "antd";
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import request from "@/api/index";
import ContentHeader from "@/Containers/ContentHeader";
import SearchList from "./SearchList";
import Main from "@/Containers/main";
import { openTab } from "@/util/menTab";
import moment from "moment";

const ArticleList = (props) => {
  const [dataSoure, setDataSource] = useState([]); // 表格数据源
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 表格选中数据源
  const [total, setTotal] = useState(0); // 数据总量
  const [pageSize, setPageSie] = useState(1); // 当前页码
  const [pageNum, setpageNum] = useState(10); // 当前分页Size
  const [category, setCategory] = useState([]);
  useEffect(() => {
    initData();
  }, [pageSize, pageNum]);
  useEffect(() => {
    request({
      url: "v1/article/category",
      method: "GET",
    }).then((res) => {
      setCategory(res.content);
    });
  }, []);

  /**
   * @description: 初始化应用数据
   * @param {*} data 查询条件
   * @return {*}
   */
  const initData = (data) => {
    request({
      url: "v1/article/list",
      method: "GET",
      params: {
        ...data,
        pageSize,
        pageNum,
      },
    }).then((res) => {
      const { content, total } = res;
      setDataSource(content);
      setTotal(total);
    });
  };

  const handleEdit = (articleId) => {
    openTab({
      key: `/article/write/new`,
      name: "写文章",
    });
    props.history.push(`/article/write/${articleId}`);
  };

  /**
   * @description: 重新设置分页信息
   * @param {*} current
   * @param {*} size
   * @return {*}
   */
  const onShowSizeChange = (current, size) => {
    setPageSie(current);
    setpageNum(size);
  };
  // 表格列
  function columns() {
    const columns = [
      {
        title: "序号",
        dataIndex: "userId",
        key: "userId",
        width: 80,
        render: (text, record, index) => {
          return <span>{index + 1}</span>;
        },
      },
      {
        title: "文章名称",
        dataIndex: "articleName",
        width: 140,
        key: "articleName",
      },
      {
        title: "文章分类",
        dataIndex: "category",
        width: 240,
        key: "category",
        render: (value) => {
          const tags = value.split(",");
          return tags.map((d) => (
            <Tag style={{ color: "#fff" }} color="#108ee9">
              {d}
            </Tag>
          ));
        },
      },
      {
        title: "创建日期",
        dataIndex: "creationDate",
        width: 240,
        key: "creationDate",
        render: (value) => {
          return <span>{moment(value).format("YYYY-MM-DD hh: mm: ss")}</span>;
        },
      },
      {
        title: "作者",
        dataIndex: "author",
        width: 240,
        key: "author",
      },
      {
        title: "描述",
        dataIndex: "description",
        key: "description",
        width: 240,
      },

      {
        title: "封面图",
        dataIndex: "articleCover",
        width: 240,
        key: "articleCover",
        render: (value) => {
          const defaultSrc =
            "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.616pic.com%2Fys_bnew_img%2F00%2F04%2F81%2FRWvymh6QCe.jpg&refer=http%3A%2F%2Fpic.616pic.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650703899&t=f48d19e4c65b3035704094ee6b298840";
          return <Image src={value} width={200} height={60} />;
        },
      },
      {
        title: "操作",
        width: 240,
        render: (value, record) => {
          return (
            <Space>
              <a onClick={() => handleDetail(record.articleId, true)}>详情</a>
            </Space>
          );
        },
      },
    ];
    return columns;
  }
  /**
   * @description: 跳转至文章详情页
   * @param {*} articleId
   * @return {*}
   */
  const handleDetail = (articleId, state) => {
    openTab({
      key: `/article/write/${articleId}`,
      name: "文章详情"
    })
    props.history.push(`/article/write/${articleId}`, {
      state,
    });
  };

  const handleToWriteArticle = () => {
    openTab({
      key: "/article/write/new",
      path: "/article/write/new",
      name: "写文章",
    });
    props.history.push("/article/write/new");
  };

  /**
   * @description: 进行批量删除
   * @param {*}
   * @return {*}
   */
  const batchDeleteArticles = () => {
    request({
      url: "v1/article/list/delete",
      method: "DELETE",
      data: selectedRowKeys,
    }).then((res) => {
      if (!res.failed) {
        notification.success({
          message: res.message,
        });
        initData();
      }
    });
  };
  const onSelectChange = (e) => {
    setSelectedRowKeys(e);
  };
  const rowSelection = {
    onChange: onSelectChange,
  };
  return (
    <>
      <ContentHeader title="文章列表管理">
        <Space>
          <Button
            type="primary"
            onClick={() => batchDeleteArticles()}
            disabled={selectedRowKeys.length === 0}
          >
            删除
          </Button>
          <Button type="primary" onClick={() => handleToWriteArticle()}>
            写文章
          </Button>
        </Space>
      </ContentHeader>
      <Main>
        <SearchList initData={initData} category={category} />
        <Table
          dataSource={dataSoure}
          columns={columns()}
          bordered
          rowKey="articleId"
          rowSelection={{
            type: "checkbox",
            ...rowSelection,
          }}
          scroll={{ x: 1300 }}
          style={{
            marginTop: 10,
          }}
          pagination={{
            pageSize: pageNum,
            total,
            current: pageSize,
            showTotal: (total) => `共${total}条`,
            onChange: onShowSizeChange,
            showSizeChanger: true,
          }}
        ></Table>
      </Main>
    </>
  );
};
const mapState = (state) => {
  return state.counter;
};
const mapAction = (dispatch) => {
  return {
    countAdd: (data) => {
      dispatch({
        type: "COUNT_ADD",
        payload: { data },
      });
    },
  };
};
export default connect(mapState, mapAction)(ArticleList);
